/**
 * Created with JetBrains WebStorm.
 * User: Administrator
 * Date: 14-6-17
 * Time: 上午9:39
 * To change this template use File | Settings | File Templates.
 */
define(function(require,exports,module){
    var VERSION = '1.0.0',
        jQuery = $ = require("jquery-1.8.2.min");

    var defaults = {
        mails:["",'@qq.com', '@163.com', '@sina.com', '@gmail.com', '@126.com', '@139.com', '@189.com', '@sohu.com', '@msn.com', '@hotmail.com'],
        afterselect: $.noop,
        width:null,
        offsetTop:0,
        offsetLeft:0,
        zIndex:1000
    };

    function parseRegExp(pattern,attributes){
        var imp = /[\^\.\\\|\(\)\*\+\-\$\[\]\?]/g;
        var imp_c = {};
        imp_c['^'] = '\\^';
        imp_c['.'] = '\\.';
        imp_c['\\'] = '\\\\';
        imp_c['|'] = '\\|';
        imp_c['('] = '\\(';
        imp_c[')'] = '\\)';
        imp_c['*'] = '\\*';
        imp_c['+'] = '\\+';
        imp_c['-'] = '\\-';
        imp_c['$'] = '\$';
        imp_c['['] = '\\[';
        imp_c[']'] = '\\]';
        imp_c['?'] = '\\?';
        pattern = pattern.replace(imp,function(o){
            return imp_c[0]
        });
        return new RegExp(pattern,attributes);
    }

    function autoEmail(element,options){
        this.$elem = $(element);
        this.options = $.extend({},defaults,options);
        this.init()
    }
    autoEmail.prototype = {
        init:function(){
            var $elem = this.$elem;
            $elem.attr("autocomplete",'off').addClass('wd_autoEmail');

            this._bindEvent();
        },

        createLists:function(value,mails){
            var lists= '',
                hasAt = /@/.test(value);
            if(hasAt){
                var arr = value.split('@');
                if(arr.length > 2) return false;
                value = arr[0];
                var regx = parseRegExp('@' + arr[1],'i');
            }

            value = hasAt ? value.split('@')[0] : value;

            for(var i = 0,len = mails.length;i < len;i++){
                if(hasAt && !regx.test(mails[i])) continue;
                lists += '<li title="' + value + mails[i] + '"><p>' + value + mails[i] + '</p></li>';
            }

            return lists.replace(/^<li([^>]*)>/, '<li$1 class="active">');
        },

        changeActive:function(panle,up){
            if(panle.css("display") === 'none') return;
            var liActive = panle.find('li.active');

            if(up){
                var liPrev = liActive.prev();
                liPrev = liPrev.length ? liPrev : panle.find("li:last");
                liActive.removeClass('active');
                liPrev.addClass('active');
            }else{
                var liNext = liActive.next();
                liNext = liNext.length ? liNext : panle.find("li:first");
                liActive.removeClass('active');
                liNext.addClass('active');
            }
        },

        toggleTip:function(val,panle,mails){
            if(!val || /^[_]|[^A-Za-z@_\d\u4E00-\u9FA5]|\s|^@/.test(val) || val.split('@').length > 2){
                panle.hide();
            }else{
                var lists = this.createLists(val,mails);
                if(lists){
                    panle.html(lists).show();
                }else{
                    panle.hide();
                }
            }
        },

        _bindDocument:function(){
            var that = this;
            $(document).bind('click.autoEamil',function(e){
                if(e.target === that.$elem[0]) return;
                that.listPanle.hide();
            })
        },

        _bindEvent:function(){
            var $elem = this.$elem;
            var that = this;
            var offset = $elem.offset(),
                emailInput_width = $elem.outerWidth(true),
                emailInput_height = $elem.outerHeight(true);
            $elem.bind("keyup.autoEmail",function(e){
                var target = $(this);
                var listPanle = null;
                var keyCode = e.keyCode;
                if(!target.data('mailTip')){
                    that.listPanle = listPanle = $('<ul class="mailtip" style="z-index:'+that.options.zIndex+'"></ul>');
                    $("body").append(listPanle);
                    listPanle.css({
                        top:offset.top + emailInput_height,
                        left:offset.left,
                        width:that.options.width || emailInput_width
                    });

                    listPanle.delegate('li','mouseenter mouseleave click',function(e){
                        switch (e.type){
                            case 'mouseenter':
                                $(this).addClass('hover');
                                break;
                            case 'click':
                                var text = $(this).attr('title');
                                target.val(text).focus();
                                that.options.afterselect.call(this,text);
                                break;
                            case 'mouseleave':
                                $(this).removeClass('hover');
                                break;
                            default:
                                break;
                        }
                    });
                    target.data('mailTip',listPanle);
                }

                listPanle = target.data('mailTip');
                var val = target.val();

                switch(keyCode){
                    case 9:
                        break;
                    case 13:
                        break;
                    case 38:
                        break;
                    case 40:
                        break;
                    default:
                        that.toggleTip(val,listPanle,that.options.mails);
                        break;
                }
                that._bindDocument();
            }).bind("keydown.autoEmail",function(e){
                    var listPanle = $elem.data('mailTip');
                    if(!listPanle) return;
                    switch (e.keyCode){
                        case 9:
                            listPanle.hide();
                        case 38:
                            that.changeActive(listPanle,true);
                            break;
                        case 40:
                            that.changeActive(listPanle);
                            break;
                        case 13:
                            if(listPanle.css('display') === 'none') return false;
                            var text = listPanle.find("li.active").attr('title');
                            $elem.val(text).focus();
                            listPanle.hide();
                            e.preventDefault();
                            that.options.afterselect.call(this,text);
                            break;
                        default:
                            break;
                    }
                })
        }
    };

    return autoEmail;
});